$(function () {
    getMsg();
    gettabfun();
    selectPage();
    //查询
    $("#findbtn").click(function () {
        var cont = $("#inputfind").val();
        if (cont == "") {
            $("#findperson").children().children().children(".modal-body")
                .children("p").text("无输入内容");
        } else {
            $.ajax({
                url: "http://101.37.30.70:8080/emp/"+cont,
                type: "get",
                traditional: true,
                success: function (response) {
                    if (response["dId"] == "0"){
                        response["dId"] = "开发部";
                    } else {
                        response["dId"] = "测试部";
                    }
                    $("#findperson").children().children().children(".modal-body")
                        .children("p").text("empName: "+response["empName"]+
                    " ,\nemail: "+response["email"]+" ,\ngender: "+response["gender"]+
                    " ,\ndeptName: "+response["dId"]);
                },
                error: function (xhr) {
                    console.log(xhr.status);
                }
            });

        }
    });
    $("#checkall").click(function () {
        if ($(this).is(":checked")) {
            $(".table tr td input[type=checkbox]").prop("checked", true);
            $("#delbtn").prop("disabled", false);
            $(".table tr td input[type=checkbox]").parent().parent().children(".btntd")
                .children(".btn-danger").prop("disabled", false);
        } else {
            $(".table tr td input[type=checkbox]").prop("checked", false);
            $("#delbtn").prop("disabled", true);
            $(".table tr td input[type=checkbox]").parent().parent().children(".btntd")
                .children(".btn-danger").prop("disabled", true);
        }
    });
    //多选
    $(".table tbody").delegate($(".table tr td" +
        " input[type=checkbox]"), "click", function (event) {
        event = event || window.event;
        isAllChicked();
        if ($(event.target).is(":checked")) {
            $(event.target).parent().parent().children(".btntd")
                .children(".btn-danger").prop("disabled", false);
        } else {
            $(event.target).parent().parent().children(".btntd")
                .children(".btn-danger").prop("disabled", true);
        }
    });
    //保存
    $("#savebtn").click(function () {
        var t1 = $("#exampleFormControlInput1").val();
        var t2 = $("#exampleFormControlInput2").val();
        var g1 = $("#addgender input[type=radio]:checked").val();
        var o1 = $("#adddept option:selected").val();
        if (g1 == 1){
            g1 = "男";
        } else {
            g1 = "女";
        }
        var obj1 = $("#exampleFormControlInput1");
        var obj2 = $("#exampleFormControlInput2");
        $("#exampleFormControlInput1").focus(checkname(obj1));
        $("#exampleFormControlInput2").focus(checkemail(obj2));
        var message = {
            "empName":t1,
            "gender":g1,
            "email":t2,
            "dId":o1};

        if(checkname(obj1) && checkemail(obj2)){
            $.ajax({
               url: "http://101.37.30.70:8080/emp",
               contentType: "application/json;charset=UTF-8",
               type: "post",
               traditional:true,
                data: JSON.stringify(message),
                success: function (result) {
                    selectPage();
                    gettabfun();
                    console.log("保存成功");
                },
                error: function (xhr) {
                    console.log(xhr.status);
                }
            });

        }
        });
        //编辑保存按钮
        $("#editbtn").click(function () {
            var editId = $(this).parent().parent().children("th").text();
            var newt1 = $("#editInput1").val();
            var newt2 = $("#editInput2").val();
            var newg1 = $("#editgender input[type=radio]:checked").val();
            var newo1 = $("#editdept select option:selected").val();
            var obj1 = $("#editInput1");
            var obj2 = $("#editInput2");
            $("#editInput1").focus(checkname(obj1));
            $("#editInput2").focus(checkemail(obj2));
            if (newg1 == 1){
                newg1 = "男";
            } else {
                newg1 = "女";
            }
            var message = {
                "empName": newt1,
                "email": newt2,
                "gender": newg1,
                "deptName": newo1
            };
            $.ajax({
                url: "http://101.37.30.70:8080/emp/"+editId,
                type: "post",
                traditional: true,
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(message),
                success: function (msg) {
                    selectPage();
                    gettabfun();
                    alert("修改成功");
                },
                error: function (xhr) {
                    console.log(xhr.status);
                }
            });

        });
        //删除
        $(".table tbody").delegate(".tddelbtn", "click", function (event) {
            var name = $(this).parent().parent().children().eq(2).text();
            var id = $(this).parent().parent().children().eq(1).text();
            var arr = new Array();
            arr.push(id);
            if (confirm("是否删除 " + name)) {
                $.ajax({
                    url: "http://101.37.30.70:8080/emp/"+arr,
                    type: "delete",
                    traditional: true,
                    data: {
                        "ids": arr
                    },
                    success: function (msg) {
                        selectPage();
                        gettabfun();
                        alert(name + " 删除成功");
                    },
                    error: function (xhr) {
                        console.log(xhr.status);
                    }
                });

            } else {
                $(this).parent().parent().children().eq(0)
                    .children("input[type=checkbox]").prop("checked", false);
            }
        });
        //多删除
        $("#delbtn").click(function () {
            var arr = new Array();
            var len = $(".table tbody tr td input[type=checkbox]:checked").length;
            for (var i = 0; i < len; i++) {
                var content = $(".table tbody tr td" +
                    " input[type=checkbox]:checked").eq(i).parent().next().text();
                arr.push(content);
            }
            var empty = "";
            for (var i=0;i<arr.length;i++){
                if (i != arr.length-1){
                    empty += arr[i];
                    empty += ",";
                } else {
                    empty += arr[i];
                }

            }
            if (confirm("是否删除选中")) {
                $.ajax({
                    url: "http://101.37.30.70:8080/emp/"+empty,
                    type: "delete",
                    traditional: true,
                    success: function (msg) {
                        selectPage();
                        gettabfun();
                    },
                    error: function (xhr) {
                        console.log(xhr.status);
                    }
                });

            }
        });
        //点击编辑
        $(".table tbody").delegate(".tdeditbtn", "click", function (event) {

            var t1 = $(this).parent().parent().children().eq(2).text();
            var t2 = $(this).parent().parent().children().eq(3).text();
            var g1 = $(this).parent().parent().children().eq(4).text();
            var o1 = $(this).parent().parent().children().eq(5).text();
            // console.log(t1 + t2 + g1 + o1);
            //Mark aaa@gmail.com 男 测试部
            $("#editInput1").val(t1);
            $("#editInput2").val(t2);
            if (g1 === "男") {
                $("#editgender input[type=radio]").eq(0).prop("checked", true);
                $("#editgender input[type=radio]").eq(1).prop("checked", false);
            } else {
                $("#editgender input[type=radio]").eq(0).prop("checked", false);
                $("#editgender input[type=radio]").eq(1).prop("checked", true);
            }
            if (o1 === "开发部") {
                $("#editdept").children("div").children("select")
                    .children("option").eq(0).prop("selected", true);
                $("#editdept").children("div").children("select")
                    .children("option").eq(1).prop("selected", false);
            } else {
                $("#editdept").children("div").children("select")
                    .children("option").eq(0).prop("selected", false);
                $("#editdept").children("div").children("select")
                    .children("option").eq(1).prop("selected", true);
            }
        });

    });

//分页
    function selectPage() {
        $.get("http://101.37.30.70:8080/emps", function (data) {

            for (var i =0;i<data.length;i++){
                if (data[i]["dId"]=="1") {
                    data[i]["dId"] = "开发部";
                }else{
                    data[i]["dId"] = "测试部";
                }
            }
            var pageSize = 5;//每页显示数
            var page = 1;//设置页码
            if (page = 1) {
                $("#prevent").parent().addClass("disabled");
            }
            paging(page);
            $("#prevent").click(function () {
                $("#checkall").prop("checked", false);
                $("#delbtn").prop("disabled", true);
                if (page > 1) {
                    page--;
                    paging(page);
                    $("#next").parent().removeClass("disabled");
                } else if (page == 1) {
                    $("#prevent").parent().addClass("disabled");
                }
                // 1 2 3 4 5 -> 6 7 8 9 10 -> 11 12 13 14 15
                //page 一开始为 2
                var p = Math.ceil(data.length / 5);//有多少页 10
                var num = p / 5;//有几份 2
                //page = 5 要换
                for (var j = Math.ceil(num); j > 0; j--) {
                    if (page == j*5) {
                        $(".pagebtn").eq(0).text(page - 4);
                        $(".pagebtn").eq(1).text(page - 3);
                        $(".pagebtn").eq(2).text(page - 2);
                        $(".pagebtn").eq(3).text(page - 1);
                        $(".pagebtn").eq(4).text(page - 0);
                    }
                }
            });
            $(".pagebtn").click(function () {
                $("#checkall").prop("checked", false);
                $("#delbtn").prop("disabled", true);
                page = $(this).text();
                if (page == 1) {
                    $("#prevent").parent().addClass("disabled");
                } else if (page == Math.ceil((data.length / 5))) {
                    $("#next").parent().addClass("disabled");
                } else {
                    $("#prevent").parent().removeClass("disabled");
                    $("#next").parent().removeClass("disabled");
                }
                paging(page);

            });
            $("#next").click(function () {
                $("#checkall").prop("checked", false);
                $("#delbtn").prop("disabled", true);
                if (page < Math.ceil(data.length / 5)) {
                    page++;
                    paging(page);
                    $("#prevent").parent().removeClass("disabled");
                } else {
                    $(this).parent().addClass("disabled");
                }
                // 1 2 3 4 5 -> 6 7 8 9 10 -> 11 12 13 14 15
                //page 一开始为 2
                var p = Math.ceil(data.length / 5);//有多少页 10
                var num = p / 5;//有几份 2
                //page = 5 10要换页
                for (var j = 1; j < num; j++) {
                    if (page == j * 5 + 1) { //j*5 -> 5 10
                        $(".pagebtn").eq(0).text(page);
                        $(".pagebtn").eq(1).text(page + 1);
                        $(".pagebtn").eq(2).text(page + 2);
                        $(".pagebtn").eq(3).text(page + 3);
                        $(".pagebtn").eq(4).text(page + 4);
                    }
                }

            });

            //分页函数
            function paging(page) {
                $(".table tbody tr").remove();
                var pagestart = (page - 1) * pageSize;
                var pageend = page * pageSize;
                var d = data.slice(pagestart, pageend);
                for (var i in d) {
                    var $t = $("<tr>\n" +
                        "                <td>\n" +
                        "                    <input type=\"checkbox\"\n" +
                        "                           aria-label=\"Radio button for following text input\">\n" +
                        "                </td>\n" +
                        "                <th scope=\"row\">" + d[i]["empId"] + "</th>\n" +
                        "                <td>" + d[i]["empName"] + "</td>\n" +
                        "                <td>" + d[i]["email"] + "</td>\n" +
                        "                <td>" + d[i]["gender"] + "</td>\n" +
                        "                <td>" + d[i]["dId"] + "</td>\n" +
                        "                <td class='btntd'>\n" +
                        "                    <button type=\"button\"" +
                        " class=\'btn btn-info btn-secondary btn-sm" +
                        " tdeditbtn'" +
                        "  data-toggle=\"modal\"\n" +
                        "                            data-target=\"#editperson\">\n" +
                        "                        <span></span>\n" +
                        "                        编辑\n" +
                        "                    </button>\n" +
                        "                    <button" +
                        " type=\"button\" class=\"btn btn-danger" +
                        " btn-primary btn-sm tddelbtn\" disabled>\n" +
                        "                        删除\n" +
                        "                    </button>\n" +
                        "                </td>\n" +
                        "            </tr>");
                    $(".table tbody").append($t);
                }
            }
        }, 'json');
    }


    function isAllChicked() {
        var uclen = $(".table tr td input[type=checkbox]").length;
        var clen = $(".table tr td input[type=checkbox]:checked").length;
        if (uclen == clen) {
            $("#checkall").prop("checked", true);
        } else {
            $("#checkall").prop("checked", false);
        }
        if (clen > 0) {
            $("#delbtn").prop("disabled", false);
        } else {
            $("#delbtn").prop("disabled", true);
        }
    }

    function getMsg() {
        $(".table tbody tr").remove();

        $.get("http://101.37.30.70:8080/emps", function (data, status) {
            for (var i = 0; i < 5; i++) {
                if (data[i]["dId"]=="1") {
                    data[i]["dId"] = "开发部";
                }else{
                    data[i]["dId"] = "测试部";
                }
                var $t = $("<tr>\n" +
                    "                <td>\n" +
                    "                    <input type=\"checkbox\"\n" +
                    "                           aria-label=\"Radio button for following text input\">\n" +
                    "                </td>\n" +
                    "                <th scope=\"row\">" + data[i]["empId"] + "</th>\n" +
                    "                <td>" + data[i]["empName"] + "</td>\n" +
                    "                <td>" + data[i]["email"] + "</td>\n" +
                    "                <td>" + data[i]["gender"] + "</td>\n" +
                    "                <td>" + data[i]["dId"] + "</td>\n" +
                    "                <td class='btntd'>\n" +
                    "                    <button type=\"button\"" +
                    " class=\'btn btn-info btn-secondary btn-sm" +
                    " tdeditbtn'" +
                    "  data-toggle=\"modal\"\n" +
                    "                            data-target=\"#editperson\">\n" +
                    "                        <span></span>\n" +
                    "                        编辑\n" +
                    "                    </button>\n" +
                    "                    <button type=\"button\"" +
                    " class=\"btn btn-danger btn-primary btn-sm" +
                    " tddelbtn\"" +
                    " disabled>\n" +
                    "                        删除\n" +
                    "                    </button>\n" +
                    "                </td>\n" +
                    "            </tr>");
                $(".table tbody").append($t);
            }
        }, 'json');
    }

    function checkname(obj) {
        var name = obj.val();
        //六位数和字母组合或2-5位中文
        var regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})";
        if (name == "") {
            obj.addClass("alert-danger");
            obj.parent().next("div").removeClass("none");
            obj.parent().next("div").text("empName can't be none");
            return false;
        } else if (!name.match(regx)) {
            obj.addClass("alert-danger");
            obj.parent().next("div").removeClass("none");
            obj.parent().next("div").text("empName should in rules");
            return false;
        } else {
            obj.removeClass("alert-danger");
            obj.parent().next("div").addClass("none");
            return true;
        }
    }
    function checkemail(obj) {
        var email = obj.val();
        var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
        if (email == "") {
            obj.addClass("alert-danger");
            obj.parent().next("div").removeClass("none");
            obj.parent().next("div").text("email can't be none");
            return false;
        } else if (!email.match(reg)) {
            obj.addClass("alert-danger");
            obj.parent().next("div").removeClass("none");
            obj.parent().next("div").text("email should in rules");
            return false;
        } else {
            obj.removeClass("alert-danger");
            obj.parent().next("div").addClass("none");
            return true;
        }
    }
function gettabfun(){
    $.get('http://101.37.30.70:8080/emps',function (data) {

        var Allarr = new Array();
        for (var i=0;i<52;i++){
            Allarr[i] = new Array();
        }
        var stuarr =
            ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
                "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
        var lenarr = new Array();
        for(var i=0;i<data.length;i++){
            for (var j=0;j<stuarr.length;j++){
                if (data[i]["empName"].charAt(0) == stuarr[j]) {
                    Allarr[j].push(stuarr[j]);
                }
            }
        }

        for (var i=0;i<Allarr.length;i++){
            lenarr.push(Allarr[i].length);
        }
        var varr = new Array();
        for (var i=0;i<lenarr.length;i++){
            varr.push(lenarr[i]/data.length);
        }
        var myChart = echarts.init(document.getElementById("main"));
        var myChart1 = echarts.init(document.getElementById("main1"));
        option = {
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b}: {c} ({d}%)"
            },
            legend: {
                orient: 'vertical',
                type: "scroll",
                right: 10,
                top: 20,
                bottom: 20,
                data:["name include of A","name include of B","name include of C","name include of D","name include of E",
                    "name include of F","name include of G","name include of H","name include of I","name include of J",
                    "name include of K","name include of L","name include of M","name include of N","name include of O",
                    "name include of P","name include of Q","name include of R","name include of S","name include of T",
                    "name include of U","name include of V","name include of W",
                    " include of X","name include of Y","name" +
                    " include of Z","name include of a","name" +
                    " include of b","name include of c","name" +
                    " include of d","name include of e",
                    "name include of f","name include of g","name" +
                    " include of h","name include of i","name" +
                    " include of j",
                    "name include of k","name include of l","name" +
                    " include of m","name include of n","name" +
                    " include of o",
                    "name include of p","name include of q","name" +
                    " include of r","name include of s","name" +
                    " include of t",
                    "name include of u","name include of v","name" +
                    " include of w","name" +
                    " include of x","name include of y","name" +
                    " include of z"]
            },
            series: [
                {
                    name:"name",
                    type:'pie',
                    radius: ['30%', '50%'],
                    avoidLabelOverlap: false,
                    label: {
                        normal: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            show: true,
                            textStyle: {
                                fontSize: '15',
                                fontWeight: 'bold'
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data:[
                    {value:varr[0]*100, name:'name include of A'},
                    {value:varr[1]*100, name:'name include of B'},
                    {value:varr[2]*100, name:'name include of C'},
                    {value:varr[3]*100, name:'name include of D'},
                    {value:varr[4]*100, name:'name include of E'},
                    {value:varr[5]*100, name:'name include of F'},
                    {value:varr[6]*100, name:'name include of G'},
                    {value:varr[7]*100, name:'name include of H'},
                    {value:varr[8]*100, name:'name include of I'},
                    {value:varr[9]*100, name:'name include of J'},
                    {value:varr[10]*100, name:'name include of K'},
                    {value:varr[11]*100, name:'name include of L'},
                    {value:varr[12]*100, name:'name include of M'},
                    {value:varr[13]*100, name:'name include of N'},
                    {value:varr[14]*100, name:'name include of O'},
                    {value:varr[15]*100, name:'name include of P'},
                    {value:varr[16]*100, name:'name include of Q'},
                    {value:varr[17]*100, name:'name include of R'},
                    {value:varr[18]*100, name:'name include of S'},
                    {value:varr[19]*100, name:'name include of T'},
                    {value:varr[20]*100, name:'name include of U'},
                    {value:varr[21]*100, name:'name include of V'},
                    {value:varr[22]*100, name:'name include of W'},
                    {value:varr[23]*100, name:'name include of X'},
                    {value:varr[24]*100, name:'name include of Y'},
                    {value:varr[25]*100, name:'name include of Z'},
                    {value:varr[26]*100, name:'name include of a'},
                    {value:varr[27]*100, name:'name include of b'},
                    {value:varr[28]*100, name:'name include of c'},
                    {value:varr[29]*100, name:'name include of d'},
                    {value:varr[30]*100, name:'name include of e'},
                    {value:varr[31]*100, name:'name include of f'},
                    {value:varr[32]*100, name:'name include of g'},
                    {value:varr[33]*100, name:'name include of h'},
                    {value:varr[34]*100, name:'name include of i'},
                    {value:varr[35]*100, name:'name include of j'},
                    {value:varr[36]*100, name:'name include of k'},
                    {value:varr[37]*100, name:'name include of l'},
                    {value:varr[38]*100, name:'name include of m'},
                    {value:varr[39]*100, name:'name include of n'},
                    {value:varr[40]*100, name:'name include of o'},
                    {value:varr[41]*100, name:'name include of p'},
                    {value:varr[42]*100, name:'name include of q'},
                    {value:varr[43]*100, name:'name include of r'},
                    {value:varr[44]*100, name:'name include of s'},
                    {value:varr[45]*100, name:'name include of t'},
                    {value:varr[46]*100, name:'name include of u'},
                    {value:varr[47]*100, name:'name include of v'},
                    {value:varr[48]*100, name:'name include of w'},
                    {value:varr[49]*100, name:'name include of x'},
                    {value:varr[50]*100, name:'name include of y'},
                    {value:varr[51]*100, name:'name include of z'}
                    ]
                }
            ]
        };
        var sexarr = new Array();
        for (var j=0;j<2;j++){
            sexarr[j] = new Array();
        }
        for (var i=0;i<data.length;i++){
            if (data[i]["gender"] == "男"){
                sexarr[0].push(data[i]);
            } else {
                sexarr[1].push(data[i]);
            }
        }

        option1 = {
            color: ['#3398DB'],
            tooltip : {
                trigger: 'axis',
                axisPointer : {
                    type : 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '25%',
                bottom: '3%',
                containLabel: true
            },
            xAxis : [
                {
                    type : 'category',
                    data : ['男', '女'],
                    axisTick: {
                        alignWithLabel: true
                    }
                }
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : [
                {
                    name:'count',
                    type:'bar',
                    barWidth: '30%',
                    data:[sexarr[0].length, sexarr[1].length]
                }
            ]
        };
        myChart.setOption(option);
        myChart1.setOption(option1);
    },'json');
}